package org.tgcloud.group.service.manager;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjDepart;
import org.tgcloud.group.entity.SysManagerUser;
import org.tgcloud.group.repository.MjDepartMapper;
import org.tgcloud.group.repository.SysManagerUserMapper;
import org.tgcloud.group.web.controller.dto.depart.DepartDTO;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhy
 * @create: 2023-11-06 10:54
 * @description:
 */
@Service
public class DepartManageService {

    @Autowired
    private MjDepartMapper departMapper;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    public APPResultMessage doAddDepart(String departName, String managerUserIds, Integer pid, Integer sort) {
        MjDepart depart = new MjDepart();
        depart.setDeptName(departName);
        depart.setStatus((short) 1);
        if (StringUtil.isNotBlank(managerUserIds)){
            depart.setManagerUserIds(managerUserIds);
        }
        depart.setPid(pid);
        depart.setSort(sort);
        departMapper.insert(depart);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<Object, DepartDTO> getDepartList(String departName) {
        List<MjDepart> mjDeparts = departMapper.selectListByDepartName(departName);
        List<DepartDTO> departList = getDepartList(mjDeparts);
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(departList);
        message.setResult(resultMessage);
        return message;
    }

    public List<DepartDTO> getDepartList(List<MjDepart> departList){
        List<DepartDTO> list = new ArrayList<>();
        for (MjDepart depart : departList){
            DepartDTO departDTO = new DepartDTO();
            BeanUtils.copyProperties(depart, departDTO);
            if (StringUtil.isNotBlank(depart.getManagerUserIds())){
                List<String> nameList = managerUserMapper.selectUsernameByIds(depart.getManagerUserIds().split(","));
                departDTO.setDepartManagerUsernames(String.join(",", nameList));
            }
            if (depart.getPid() != null){
                departDTO.setPDeptName(departMapper.getNameById(depart.getPid()));
            }
            list.add(departDTO);
        }
        return buildDepartmentTree(list);
    }

    public static List<DepartDTO> buildDepartmentTree(List<DepartDTO> departList) {
        if (departList == null || departList.isEmpty()) {
            return Collections.emptyList();
        }
        // 1. 使用 Map 通过 id 快速查找部门对象
        Map<Integer, DepartDTO> departMap = new HashMap<>();
        for (DepartDTO depart : departList) {
            departMap.put(depart.getId(), depart);
        }
        // 2. 遍历所有部门，构建父子关系
        for (DepartDTO depart : departList) {
            Integer pid = depart.getPid();
            if (pid != null && departMap.containsKey(pid)) {
                // 如果父部门存在，将当前部门添加到父部门的 subList 中
                DepartDTO parent = departMap.get(pid);
                if (parent.getSubList() == null) {
                    parent.setSubList(new ArrayList<>());
                }
                parent.getSubList().add(depart);
            }
        }
        // 3. 收集根节点（pid 为 null 或 0）
        List<DepartDTO> rootNodes = new ArrayList<>();
        for (DepartDTO depart : departList) {
            if (depart.getPid() == null || depart.getPid() == 0) {
                rootNodes.add(depart);
            }
        }
        return rootNodes;
    }

    public APPResultMessage doUpdateDepart(Integer id, String departName, String managerUserIds, Integer pid, Integer sort) {
        departMapper.updateMsgById(id, departName, managerUserIds, pid, sort);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doDelDepart(Integer id) {
        departMapper.updateStatusById(id, (short) 10);
        return APPResultMessage.getSuccessMessage();
    }

    // 获取部门信息
    public List<MjDepart> doGetDepartByManageUserId(Integer userId) {
        SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(userId);
        List<MjDepart> departList = departMapper.selectListByIds(managerUser.getDepartIds().split(","));
        return departList;
    }

    // 获取个人所属部门的部门名称
    public String doGetDepartNameByManageUserId(Integer userId) {
        SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(userId);
        if (StringUtil.isNotBlank(managerUser.getDepartIds())){
            List<MjDepart> departList = departMapper.selectListByIds(managerUser.getDepartIds().split(","));
            return departList.stream().map(MjDepart::getDeptName).collect(Collectors.joining(","));
        }else {
            return "";
        }
    }

    // 获取个人所属的部门的负责人id
    public String doGetDepartManagerUserIdByManageUserId(Integer userId) {
        SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(userId);
        List<String> departManagerUserList = departMapper.selectManagerUserListByIds(managerUser.getDepartIds().split(","));
        List<String> ids = new ArrayList<>();
        for (String sId : departManagerUserList) {
            String[] split = sId.split(",");
            ids.addAll(Arrays.asList(split));
        }
        return ids.stream().distinct().collect(Collectors.joining(","));
    }

}
